var express = require('express');
var router = express.Router();
var { GoodsModel, OrderModel, InvoiceModel,user,ContactsModel } = require('../model/model')
var multiparty = require('multiparty')
let jwt=require('jsonwebtoken')
var xlsx=require('node-xlsx')
/* GET home page. */
/* new RegExp   populate skip limit {age:{$gte:min}}
find({$and:queryarr}) countDocuments({$and:queryarr})
form.parse*/
router.post('/sc',(req,res)=>{
  console.log(111);
  
  let form=new multiparty.Form()
  form.uploadDir='upload'
  form.parse(req,(err,a,img)=>{
    res.send({
      code:200,
      path:'http://localhost:3000/'+img.file[0].path
    })  
  })
})
// router.get('/', function (req, res, next) {
//   res.render('index', { title: 'Express' });

// });


// 获取用户数据
router.get('/user',async(req,res)=>{

let {value,_id}=req.query
let arr=[]
let arr1=[]
  //用户数据
  if(/^1[3-9]\d{9}$/.test(value)&&value){
   arr.push({telp:value})
   arr1.push({telp:value})
    
  }else if((/^[\u4e00-\u9fa5a-zA-Z0-9\s]{1,}$/.test(value))&&value){
   
     arr.push({ name: value }); 
     arr1.push({name:new  RegExp(value) })
  }
 
  
  if(_id){
    arr.push({_id:{$ne:_id}})
       // 查询当前用户的所有联系人ID
      const contactIds = await ContactsModel.find(
        { userId: _id }, // 假设联系人模型中有userId字段
        { contactId: 1 } // 只返回contactId字段
      ).distinct('contactId');
      
      // 排除所有联系人
      arr.push({ _id: { $nin: contactIds } });
  }
  let userlist=await user.find({$and:arr})
   // 查询匹配的联系人
    let userlist1 = await ContactsModel.find({ $and: arr1 });
  res.send({
    code: 200,
    userlist,
    userlist1
  })
})
// 返回联系人
router.get('/getContact',async(req,res)=>{
  console.log(2);
  
  let {_id}=req.query
 console.log(_id);
 
  
  let contact = await user.find();

  contact=contact.filter(i=>i._id!=_id)
  console.log(contact);
  


  res.send({
    code:200,
    contact
  })
})
// 商品列表接口
router.get('/Goods', async (req, res) => {
  try {
    const goods = await GoodsModel.find();
    res.send({ code: 200, data: goods });
  } catch (err) {
    res.status(500).send({ code: 500, message: "数据加载失败" });
  }
});

// 新增商品添加接口
router.post('/Goods', async (req, res) => {
  try {
    // 创建新商品文档
    const newGood = new GoodsModel({
      productCode: req.body.productCode,
      productName: req.body.productName,
      price: req.body.price,
      listingDate: new Date(req.body.listingDate),
      status: req.body.status || '已发布' // 默认已发布
    });

    // 保存到数据库
    const savedGood = await newGood.save();
    
    res.status(201).send({
      code: 201,
      message: '商品添加成功',
      data: savedGood
    });
  } catch (err) {
    console.error('添加失败:', err);
    res.status(500).send({
      code: 500,
      message: '添加失败，请检查数据格式'
    });
  }
});

// 添加订单数据接口
router.get('/Order', async (req, res) => {
  try {
    const orders = await OrderModel.find();
    res.send({ code: 200, data: orders });
  } catch (err) {
    res.status(500).send({ code: 500, message: "订单数据加载失败" });
  }
});

router.post('/Order', async (req, res) => {
  try {
    const newOrder = new OrderModel({
      productCode: req.body.productCode,
      productName: req.body.productName,
      price: req.body.price,
      listingDate: new Date(req.body.listingDate),
      pay: req.body.pay, // 添加支付类型字段
      status: req.body.status || '已发布'
    });

    const savedOrder = await newOrder.save();
    res.status(201).send({
      code: 201,
      message: '订单添加成功',
      data: savedOrder
    });
  } catch (err) {
    // ...错误处理保持不变
  }
});

// 发票数据接口
router.get('/Invoice', async (req, res) => {
  try {
    const invoice = await InvoiceModel.find();
    res.send({ code: 200, data: invoice });
  } catch (err) {
    res.status(500).send({ code: 500, message: "发票数据加载失败" });
  }
});

//添加联系人
router.post('/addContact', async (req, res) => { 
  await ContactsModel.create(req.body);
  res.send({
    code: 200,
    message: '联系人添加成功'
  });
});
// 获取数据
router.get('/getData', async (req, res) => {
 let{_id}=req.query
 if(_id){
 let data=await user.find({_id})
 res.send({
   code: 200,
   data
 });
 }else{
  res.send({
    code: 200,
    data:[]
  });
 }

})
// 修改
router.post('/update', async (req, res) => {
  let {_id}=req.body  
  console.log(req.body);
  
  await user.updateOne({_id},req.body)
  res.send({
    code: 200,
    message: '修改成功'
  });
});
module.exports = router;
